package org.example.reemploymentsys.controller;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.reemploymentsys.entity.ExamRecord;
import org.example.reemploymentsys.entity.Organization;
import org.example.reemploymentsys.entity.Student;
import org.example.reemploymentsys.repository.ExamRecordRe;
import org.example.reemploymentsys.repository.OrganizationRe;
import org.example.reemploymentsys.repository.StudentRe;
import org.example.reemploymentsys.repository.UserTbRe;
import org.example.reemploymentsys.service.ExcelService;
import org.example.reemploymentsys.tool.AliOSSutils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
public class uploadController {
    @Autowired
    private AliOSSutils aliOSSutils;
    @Autowired
    private UserTbRe userTbRe;
    @Autowired
    private OrganizationRe organizationRe;
    @Autowired
    private StudentRe studentRe;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private ExamRecordRe examRecordRe;
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        return aliOSSutils.upload(file);
    }
    @PostMapping("/uploadStudentExcel/{username}")
    public String uploadVideo(@PathVariable String username, @RequestParam("file") MultipartFile file) throws IOException {
        try {
            String OrganizationId= userTbRe.findOrgizationIdByUsername(username);
            Organization organization = organizationRe.findOrganizationById(OrganizationId);
            if (file.isEmpty()) {
                return "文件不能为空";
            }

            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            List<Student> studentList = new ArrayList<>();

            for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 跳过标题行
                Row row = sheet.getRow(i);
                if (row == null) continue;

                Student student = new Student();
                String name=excelService.getCellValueAsString(row.getCell(0));
                student.setName(name);
                student.setPhone(excelService.getCellValueAsString(row.getCell(1)));
                student.setEmail(excelService.getCellValueAsString(row.getCell(2)));
                student.setAddress(excelService.getCellValueAsString(row.getCell(3)));
                student.setPassword(excelService.getCellValueAsString(row.getCell(4)));
                student.setOrganization(organization);
//                student.setName(row.getCell(0).getStringCellValue());
//                student.setPhone(row.getCell(1).getStringCellValue());
//                student.setEmail(row.getCell(2).getStringCellValue());
//                student.setAddress(row.getCell(3).getStringCellValue());
//                student.setPassword(row.getCell(4).getStringCellValue());
//                student.setOrganization(organization);
                studentList.add(student);
            }
            studentRe.saveAll(studentList);
            //studentService.saveAll(studentList);
            return "导入成功，导入了 " + studentList.size() + " 条记录。";
        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败：" + e.getMessage();
        }
    }
    @GetMapping("/studentsExport/{username}")
    public ResponseEntity<byte[]> exportStudents(@PathVariable String username) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            String OrganizationId= userTbRe.findOrgizationIdByUsername(username);
            Sheet sheet = workbook.createSheet("Students");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "姓名", "电话", "邮箱", "地址"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(createHeaderStyle(workbook));
            }

            // 填充数据
            List<Student> students = studentRe.findAllByOrganizationId(OrganizationId);
            for (int i = 0; i < students.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Student student = students.get(i);
                row.createCell(0).setCellValue(student.getId());
                row.createCell(1).setCellValue(student.getName());
                row.createCell(2).setCellValue(student.getPhone());
                row.createCell(3).setCellValue(student.getEmail());
                row.createCell(4).setCellValue(student.getAddress());
            }

            // 写入到字节流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);

            // 设置响应头
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=students.xlsx")
                    .header(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .body(outputStream.toByteArray());

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败");
        }
    }

    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        return style;
    }
    @GetMapping("/scoreExport/{username}")
    public ResponseEntity<byte[]> exportScore(@PathVariable String username) throws IOException {
        String OrganizationId= userTbRe.findOrgizationIdByUsername(username);
        Organization organization = organizationRe.findOrganizationById(OrganizationId);
            // 获取学员考试数据
            List<ExamRecord> examRecords = examRecordRe.findAllByStudent_Organization(organization);

            // 创建工作簿和工作表
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("学员考试统计");

            // 设置表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("学员姓名");
            headerRow.createCell(1).setCellValue("考试名称");
            headerRow.createCell(2).setCellValue("得分");
            headerRow.createCell(3).setCellValue("考试状态");

            // 填充数据
            int rowNum = 1;
            for (ExamRecord examRecord : examRecords) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(examRecord.getStudent().getName());
                row.createCell(1).setCellValue(examRecord.getExam().getName());
                row.createCell(2).setCellValue(examRecord.getScore());
                row.createCell(3).setCellValue(examRecord.getIsSubmitted() ? "已完成" : "未完成");
            }

            // 将工作簿写入字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            workbook.close();

            byte[] data = baos.toByteArray();

            // 设置响应头和文件名，返回 Excel 文件
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=学员考试统计报表.xlsx");
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(data);
    }

}
